import { nextKey } from '@/widgets'
import { onMounted, onUnmounted } from 'vue'

export interface MapLegendEntry {
  name: string
  visible(): boolean
  setVisible(ok: boolean): void
}

interface MapLegendEntryX extends MapLegendEntry {
  id: string
}

export interface MapLegendEntryInfo {
  id: string
  name: string
  visible: boolean
}

function getInfo(e: MapLegendEntryX): MapLegendEntryInfo {
  return { id: e.id, name: e.name, visible: e.visible() }
}

type MapLegendListener = (info: MapLegendEntryInfo[]) => void

const listeners: MapLegendListener[] = []
const legends: MapLegendEntryX[] = []

function triggerChanged() {
  const info = legends.map(getInfo)
  for (const l of listeners) {
    try {
      l(info)
    } catch (ex) {
      console.error(ex)
    }
  }
}

export function setMapLegendVisible(id: string, ok: boolean) {
  const idx = legends.findIndex((e) => e.id === id)
  if (idx < 0) {
    return
  }
  const e = legends[idx]
  e.setVisible(ok)
  triggerChanged()
}

export function useMapLegendInfo(listener: MapLegendListener) {
  onMounted(() => {
    listeners.push(listener)
  })
  onUnmounted(() => {
    const idx = listeners.indexOf(listener)
    if (idx < 0) {
      return
    }
    listeners.splice(idx, 1)
  })
}

export function registerMapLegend(l: MapLegendEntry) {
  legends.push({
    id: nextKey(),
    name: l.name,
    visible: () => l.visible(),
    setVisible: (ok) => l.setVisible(ok)
  })
  triggerChanged()
}
